#!/usr/bin/env python
# -*- coding:utf-8 -*-
import MySQLdb

__all__ = ['Mysql']


def n(func):
    def wrapper(*args, **kwargs):
        f = func(*args, **kwargs)
        next(f, None)
        return f

    return wrapper


class Mysql:
    def __init__(self, **kwargs):
        self.min_cached = kwargs.get('min_cached', 5)
        self.host = kwargs.get('host', 'localhost')
        self.port = kwargs.get('port', 3306)
        self.user = kwargs.get('user', 'root')
        self.password = kwargs.get('password', '')
        self.database = kwargs.get('database', 'crawler')
        self.charset = kwargs.get('charset', 'utf8')
        self.db = None

    def init(self):
        self.db = MySQLdb.connect(host=self.host, port=self.port, user=self.user, passwd=self.password,
                                  db=self.database, charset=self.charset)

    @n
    def selector(self):
        """使用迭代器实现的可以多次查询的Mysql查询函数"""
        cur = self.db.cursor()
        data = []
        while True:
            sql = yield data
            if sql is None or sql == '':
                break
            cur.execute(sql)
            self.db.commit()
            data = cur.fetchall()
        cur.close()
        return

    @staticmethod
    def close_selector(selector):
        try:
            selector.send(None)
        except StopIteration:
            pass

    def close(self):
        self.db.close()

    def __del__(self):
        self.close()
